package com.cjl.jvm.gc;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class PhantomRef {
    public static class Referred{
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println("Referred 被gc");
        }
    }
    public static void collect() throws Exception{
        System.out.println("PhantomRef.collect start");
        System.gc();
        System.out.println("PhantomRef.collect end");
        Thread.sleep(2000);
    }
    public static void main(String[] args) throws Exception {
        System.out.println("创建虚引用");

        ReferenceQueue dead = new ReferenceQueue();
        Map<Reference,String> cleanUpMap = new HashMap<>();


        Referred strong = new Referred();
        PhantomReference<Referred> phantom = new PhantomReference<>(strong,dead);
        cleanUpMap.put(phantom,"需要清理");


        strong = null;
        PhantomRef.collect();

        Reference reference = dead.poll();
        if (reference != null){
            System.out.println("PhantomRef.main"+cleanUpMap.remove(reference));
        }else {
            System.out.println("PhantomRef.main reference null");
        }

        System.out.println("PhantomRef.main END");



    }
}
